package com.leetcode.partition1;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/8/4 8:39
 */
public class LC27移除元素 {

    public static int removeElement(int[] nums, int val) {
        return fastSlowIndex(nums, val);
    }

    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
//        int[] nums = { 2 };
        System.out.println(removeElement(nums, 2));
        System.out.println(Arrays.toString(nums));
    }

    private static int fastSlowIndex(int[] nums, int val) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (val != nums[fastIndex]) {
                nums[slowIndex++] = nums[fastIndex];
            }
        }
        return slowIndex;
    }

    public static int doubleIndex(int[] nums, int val) {
        if (nums.length == 0) return 0;
        //i指向数组第一个元素，j指向数组的最后一个元素
        int i = 0, j = nums.length - 1, temp;
        while (i < j) {
            //i从左往右遍历，直到遇到nums[i]是val；然后j从右往左遍历，直到遇到nums[j]!=val，交换nums[i]和nums[j]的值
            while (nums[i] != val && i < j) i++;
            while (nums[j] == val && i < j) j--;
            if (i >= j) break;
            //交换值
            temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
        return nums[i] == val ? i : i + 1;
    }
}
